package com.sp.common.oauth2.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.sp.common.model.LoginUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;
@Slf4j
@Service(value = "usernamePassword")
public class UserDetailServiceImpl implements UserDetailsService {
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        String  sotype="PC";
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        if(request!=null){
            sotype = request.getAttribute("sotype")+"";
        }
        log.info("UserDetailServiceImpl 中获取{}的登录类型{}",username,sotype);

        LoginUser userInfo = new LoginUser();
        if (ObjectUtil.isNull(userInfo)) {
            throw new InternalAuthenticationServiceException("用户信息为空");
        }

        return checkUser(userInfo);
    }


    private LoginUser checkUser(LoginUser userInfo) {
        /*
         * if (loginAppUser != null && !loginAppUser.isEnabled()) { throw new
         * DisabledException("用户已作废"); }
         */
        if(Objects.nonNull(userInfo)){
            if(userInfo.getUserId()==null){
                throw new InternalAuthenticationServiceException("用户名或密码错误");
            }
            if(!Objects.equals(userInfo.getIsEnable(),1)){
                throw new InternalAuthenticationServiceException("账号已被禁用，无法登录");
            }
            if(Objects.equals(userInfo.getIsDelete(),0)){
                throw new InternalAuthenticationServiceException("用户已删除");
            }
        }
        if (!userInfo.isAllowLogin()) {
            throw new InternalAuthenticationServiceException("用户未分配权限，请联系管理员");
        }
        return userInfo;
    }
}
